var http = require('http');
var parseUrl = require('url').parse;
http.globalAgent.maxSockets = 120;

exports.get = function( url, cb ){
	var options = parseUrl( url );
	options.method =  'GET';
	var req = http.request(options, function(res) {
			res.setEncoding('utf8');
			var ret ='';
			res.on('data', function (chunk) {
				ret += chunk;
			});
			res.on('end', function(){
				if(cb)cb( null,ret );
			});
			res.on('error', cb);
		});
	req.on('error', cb );
	req.setTimeout(30000, function(){
		if(cb) cb({code:500,msg:'fetch datasource timeout.'})
	});
	req.end();
}

exports.post = function( url, postData, cb ){
	var options = parseUrl( url );
	options.method =  'POST';
	var req = http.request(options, function(res) {
			res.setEncoding('utf8');
			var ret ='';
			res.on('data', function (chunk) {
				ret += chunk;
			});
			res.on('end', function(){
				if(cb)cb( null,ret );
			});
			res.on('error', cb);
		});

	req.on('error', cb );
	req.setTimeout(10000, function(){
		if(cb) cb({code:500,msg:'fetch datasource timeout.'})
	});

	req.write( encodeURIComponent( postData ) );
	req.end();
}
